//
//  HighScoresLayer.m
//
//  Source file for the high scores layer which shows the top 10
//  high scores for the player 
//

#import "HighScoresLayer.h"
#import "GameState.h"
#import "Reachability.h"
#import "SimpleAudioEngine.h"
#import "MainMenuLayer.h"
#import "StatisticsLayer.h"

static const int kHighScoresTitleSize = 104;
static const int kPostOnlineScore = 0;
static const int kNo = 1;

@implementation HighScoresLayer

// returns a scene object containing the current layer
// this essentially loads the "screen" for a
// particular section or part of the game
+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
    HighScoresLayer *layer = [HighScoresLayer node];
    
	[scene addChild: layer];
	
	return scene;
}

// checks internet connection by using Apple's reachability class. returns true
// if internet connection is available
- (BOOL)checkInternetConnected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return !(networkStatus == NotReachable);
}

// handler for statistics button when pressed
-(void)statisticsPressed
{
    [[CCDirector sharedDirector] replaceScene:[CCTransitionFade
                                               transitionWithDuration:0.3 scene:[StatisticsLayer scene]]];
    [[SimpleAudioEngine sharedEngine] playEffect:@"Menu_Click.wav"];
    [[SimpleAudioEngine sharedEngine] playEffect:@"Menu_Click.wav"];
    
}

// handler for main menu button when pressed
-(void) mainMenuPressed
{
    [[CCDirector sharedDirector] replaceScene:[CCTransitionFade
                                               transitionWithDuration:0.3 scene:[MainMenuLayer scene]]];
    [[SimpleAudioEngine sharedEngine] playEffect:@"Menu_Click.wav"];
}

// this is the method that handles the button press functionality of the alert boxes
// that pop up when the user attempts to post their online score
-(void) alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == kNo) {
        return;
    }
    
    // return if no internet connection
    if (buttonIndex == kPostOnlineScore) {
        if (![self checkInternetConnected]) {
            UIAlertView* dialog = [[UIAlertView alloc] init];
            [dialog setTitle:@"Internet Connection"];
            [dialog setMessage:@"You need an active internet connection to post your high score."];
            [dialog addButtonWithTitle:@"OK"];
            [dialog show];
            [dialog release];
            return;
        }
        
        GameState *gameState = [GameState sharedGameState];
        NSString *userName = [gameState userName];
        NSMutableDictionary *scoreDict = [[gameState getState:@"highscores"] mutableCopy];
        
        NSArray *userScores = [scoreDict objectForKey:userName];
        if ([userScores count] == 0) {
            UIAlertView* dialog = [[UIAlertView alloc] init];
            [dialog setTitle:@"No Score"];
            [dialog setMessage:@"You don't have any scores to post yet."];
            [dialog addButtonWithTitle:@"OK"];
            [dialog show];
            [dialog release];
            return;
        }
        
        int highestOverallScore = [[[scoreDict objectForKey:userName] valueForKeyPath:@"@max.intValue"] intValue];
        NSNumber *highPosted = [[gameState getState:@"highestposted"] objectForKey:userName];
        
        // check if high score has been posted before
        if (highPosted != nil) {
            int highestPostedScore = [highPosted intValue];
            if (highestOverallScore == highestPostedScore) {
                UIAlertView* dialog = [[UIAlertView alloc] init];
                [dialog setTitle:@"High Score"];
                [dialog setMessage:@"You have already posted your current highest score."];
                [dialog addButtonWithTitle:@"OK"];
                [dialog show];
                [dialog release];
                return;
            }
        }
        
        // create a GET request to an external website and send the name and high score of the logged in player
        // the external website has a script that adds the score to the server
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
                                        [NSURL URLWithString:[NSString stringWithFormat:@"http://inspectionapp.hostzi.com?name=%@&score=%d", userName, highestOverallScore]]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
        
        [request setHTTPMethod: @"GET"];
        
        NSError *requestError;
        NSURLResponse *urlResponse = nil;
        NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
        
        UIAlertView* dialog = [[UIAlertView alloc] init];
        [dialog setTitle:@"Status"];
        [dialog setMessage:@"Congratulations! Your high score has been sent successfully."];
        [dialog addButtonWithTitle:@"OK"];
        [dialog show];
        [dialog release];
        
        if (highPosted == nil) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:highestOverallScore] forKey:userName];
            [gameState setState:@"highestposted" value:dict];
        }
        else {
            [scoreDict setValue:[NSNumber numberWithInt:highestOverallScore] forKey:userName];
            [gameState setState:@"highestposted" value:scoreDict];
        }
    }

}

// handler for post online button
-(void)postOnlinePressed
{
    UIAlertView* dialog = [[UIAlertView alloc] init];
    [dialog setDelegate:self];
    [dialog setTitle:@"Confirmation"];
    [dialog setMessage:@"Would you like to post your highest score online to the global scoreboard?"];
    [dialog addButtonWithTitle:@"Yes"];
    [dialog addButtonWithTitle:@"No"];
    [dialog show];
    [dialog release];
    [[SimpleAudioEngine sharedEngine] playEffect:@"Menu_Click.wav"];
    
}

-(id)init
{
    if ((self = [super init])) {
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        
        CCSprite *bg = [CCSprite spriteWithFile:@"menuBackground.png"];
        bg.position = ccp(winSize.width / 2, winSize.height / 2);
        [self addChild:bg z:0];
        
        CCLabelTTF *highScoresTitleLbl = [CCLabelTTF labelWithString:@"High Scores" fontName:@"Marker Felt" fontSize:kHighScoresTitleSize];
        highScoresTitleLbl.position = ccp(winSize.width / 2, winSize.height - kHighScoresTitleSize);
        highScoresTitleLbl.color = ccc3(255, 255, 255);
        [self addChild:highScoresTitleLbl];
        
        GameState *gameState = [GameState sharedGameState];
        NSDictionary *scoreDict = [gameState getState:@"highscores"];
        NSArray *userScores = [scoreDict objectForKey:[gameState userName]];
        
        CCMenuItemImage *statisticsBtn = [CCMenuItemImage itemWithNormalImage:@"statisticsButton.png"
              selectedImage:@"statisticsButtonHighlight.png" target:self selector:@selector(statisticsPressed)];
        //statisticsBtn.position = ccp(statisticsBtn.contentSize.width / 2 + 20, statisticsBtn.contentSize.height / 2 + 20);
        
        CCMenuItemImage *postOnlineBtn = [CCMenuItemImage itemWithNormalImage:@"postOnlineButton.png"
              selectedImage:@"postOnlineButtonHighlight.png" target:self selector:@selector(postOnlinePressed)];
        //postOnlineBtn.position = ccp(winSize.width - postOnlineBtn.contentSize.width / 2 - 20, postOnlineBtn.contentSize.height / 2 + 20);
        
        CCMenuItemImage *menuBtn = [CCMenuItemImage itemWithNormalImage:@"mainMenuButton.png"
                                                          selectedImage:@"mainMenuButtonHighlight.png" target:self selector:@selector(mainMenuPressed)];
        
        CCMenu *menu = [CCMenu menuWithItems:postOnlineBtn, statisticsBtn, menuBtn, nil];
        [menu alignItemsVerticallyWithPadding:10.0];
        menu.position = ccp(winSize.width / 2, statisticsBtn.contentSize.height / 2 + 80);
        [self addChild:menu];
        

        if ([userScores count] == 0) {
            CCLabelTTF *highScoresTitleLbl = [CCLabelTTF labelWithString:@"There are currently no high scores yet." fontName:@"Marker Felt" fontSize:30];
            highScoresTitleLbl.position = ccp(winSize.width / 2, winSize.height - 300);
            highScoresTitleLbl.color = ccc3(255, 0, 0);
            [self addChild:highScoresTitleLbl];
        }
        else {
            NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];
            NSArray *sortedScores = [userScores sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

            // display the high scores for the user logged in
            for (int i = 0; i < [sortedScores count] && i < 10; ++i) {
                CCLabelTTF *highScoresTitleLbl = [CCLabelTTF labelWithString:
                        [NSString stringWithFormat:@"%d. %@ ........................................ %@", i + 1, [gameState userName],
                         [sortedScores objectAtIndex:i]] fontName:@"Marker Felt" fontSize:30];
                highScoresTitleLbl.position = ccp(winSize.width / 2, winSize.height - 250 - i * 50);
                highScoresTitleLbl.color = ccc3(0, 0, 255);
                [self addChild:highScoresTitleLbl];
            }
        }
    }
    
    return self;
}

@end
